How can I fix the UnboundLocalError in my Python if-else statement for text extraction